package xx.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class GzjsFilter implements Filter
{
    Map<String, String> headers = new HashMap<String, String>();

    public void destroy()
    {
        headers.clear();
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException
    {
        HttpServletResponse response = (HttpServletResponse) res;
        for (Iterator it = headers.entrySet().iterator(); it.hasNext();)
        {
            Map.Entry entry = (Map.Entry) it.next();
            response.addHeader((String) entry.getKey(), (String) entry.getValue());
        }
        chain.doFilter(req, res);
    }

    public void init(FilterConfig config) throws ServletException
    {
        String headersStr = config.getInitParameter("headers");
        String[] headers = headersStr.split(";");
        for (int i = 0; i < headers.length; i++)
        {
            int equal = headers[i].indexOf("=");
            this.headers.put(headers[i].substring(0, equal), headers[i].substring(equal + 1));
        }
    }
}
